/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Service;

import DB.Cita;
import DB.HibernateUtil;
import DB.HoraBloqueada;
import DB.HorarioProfesional;
import DB.Paciente;
import DB.ProgramaDipreca;
import DB.ProgramaMedicoFonasa;
import DB.ProgramaMedicoJeafosale;
import DB.Usuario;
import java.util.Date;
import java.util.List;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

/**
 *
 * @author Mario
 */
@WebService(serviceName = "AgendaWS")
public class AgendaWS {
    /**
     * Web service operation
     */
    @WebMethod(operationName = "agregarCita")
    public Long agregarCita(@WebParam(name = "cita") Cita cita) {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction trans = session.beginTransaction();
        Cita c = new Cita();
        c.setRutProfesional(cita.getRutProfesional());        
        c.setRutPaciente(cita.getRutPaciente());           
        c.setTipoPrograma(cita.getTipoPrograma());
        c.setIdPrograma(cita.getIdPrograma());        
        c.setDesdeHora(cita.getDesdeHora());        
        c.setDesdeMinuto(cita.getDesdeMinuto());        
        c.setFecha(cita.getFecha());
        c.setNumeroSesion(cita.getNumeroSesion());
        c.setObservacion(cita.getObservacion());
        c.setEstado(cita.getEstado());
        c.setVisible(true);
        session.save(c);
        trans.commit();
        return c.getId();
    }    
    /**
     * Busca las citas de un dia de un determinado profesional
     */
    @WebMethod(operationName = "buscarCitasDiariaPorProfesional")
    public List<Cita> buscarCitasDiariaPorProfesional( @WebParam(name = "rutProfesional")  String rutProfesional, @WebParam(name = "fecha") Date fecha) {
        
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            Transaction trans = session.beginTransaction();                        
            Criteria criteria = session.createCriteria( Cita.class ); 
            criteria.add( Restrictions.and(Restrictions.and(Restrictions.eq( "fecha", fecha), Restrictions.eq("visible", true)), Restrictions.eq("rutProfesional", rutProfesional)));            
            return criteria.list();        
    }        
    @WebMethod(operationName = "buscarCitasSemanaPorProfesional")
    public List<Cita> buscarCitasSemanaPorProfesional(@WebParam(name = "fechaInicio") Date fechaDesde, @WebParam(name = "fechaTermino") Date fechaHasta, @WebParam(name = "rut") String rut) {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction trans = session.beginTransaction();        
        Query q = session.createQuery("SELECT c FROM Cita c WHERE c.rutProfesional='"+rut+"' AND c.fecha BETWEEN '"+fechaDesde+"' AND '"+fechaHasta+"'");        
        return q.list();        
    }
    /**
     * Web service operation
     */
    @WebMethod(operationName = "modificarCita")
    public boolean modificarCita(Cita c){                     
        return ControladorDeObjetos.updateObject(c);
    }   
    
    /**
     * Web service operation
     */
    @WebMethod(operationName = "buscarCitasPorPaciente")
    public List<Cita> buscarCitasPorPaciente(@WebParam(name = "rut") String rut) {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction trans = session.beginTransaction();        
        Query q = session.createQuery("select c from Cita c where c.rutPaciente='"+rut+"' and c.visible=true");        
        return q.list();        
    }  
    @WebMethod(operationName = "buscarProfesionales")
     public List<Usuario> buscarProfesionales() {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction trans = session.beginTransaction();
        Query q = session.createQuery("from Usuario u where u.tipoCuenta='Profesional' AND u.activo=true");                        
        return q.list();
    }
    @WebMethod(operationName = "buscarProfesional")
    public Object buscarProfesional(@WebParam(name = "rut") String rut) {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction trans = session.beginTransaction();
        Query q = session.createQuery("from Usuario u where u.rut='"+rut+"' AND u.activo=true");                
        if(q.list().isEmpty())
            return null;        
        return q.list().get(0);                      
    }
    @WebMethod(operationName = "listarCitasPapelera")
    public List<Cita> ListarCitasPapelera() {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction trans = session.beginTransaction();
        Query q = session.createQuery("from Cita c where c.visible=false");        
        return q.list();
                
    }
    @WebMethod(operationName = "listarCitasPapeleraParaProfesional")
    public List<Cita> ListarCitasPapeleraPataProfesional(@WebParam(name = "rut") String rut) {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction trans = session.beginTransaction();
        Query q = session.createQuery("from Cita c where c.visible=false AND c.rutProfesional='"+rut+"'");        
        return q.list();
                
    }
    @WebMethod(operationName = "buscarCitaPorId")
    public Object buscarCitaPorId(@WebParam(name = "id") Long id) {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction trans = session.beginTransaction();
        Query q = session.createQuery("from Cita c where c.id="+id);                
        if(q.list().isEmpty())
            return null;
        return q.list().get(0);      
    }    
    @WebMethod(operationName = "agregarHorario")
    public boolean agregarHorarioUsuario(@WebParam(name = "horario") HorarioProfesional horario) {        
        return ControladorDeObjetos.saveObject(horario);
    }
    @WebMethod(operationName = "cargarHorarioSegunFecha")
    public Object cargarHorarioSegunFecha(@WebParam(name = "fecha") Date fecha, @WebParam(name = "rut") String rut) {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction trans = session.beginTransaction();        
        Query q = session.createQuery("SELECT h FROM HorarioProfesional h WHERE h.rut='"+rut+"' AND '"+ fecha +"' BETWEEN h.fechaInicio AND h.fechaTermino");
        if(q.list().isEmpty())
            return null;
        return q.list().get(0);        
    }
    @WebMethod(operationName = "modificarHorario")
    public boolean modificarHorario(@WebParam(name = "horario") HorarioProfesional horario){                     
        return ControladorDeObjetos.updateObject(horario);
    }
    @WebMethod(operationName = "citasPorConfirmar")
    public List<Cita> citasPorConfirmar(){                     
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction trans = session.beginTransaction();        
        Query q = session.createQuery("from Cita c where c.estado='No Confirmada' AND c.visible=true");
        return q.list();
    }
    @WebMethod(operationName = "citasPorConfirmarSegunProfesional")
    public List<Cita> citasPorConfirmarSegunProfesional(@WebParam(name = "rut") String rut){
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction trans = session.beginTransaction();        
        Query q = session.createQuery("from Cita c where c.estado='No Confirmada' AND c.rutProfesional='"+rut+"' AND c.visible=true");
        return q.list();
    }
    @WebMethod(operationName = "agregarHoraABloquear")
    public boolean agregarHoraABloquear(@WebParam(name = "hora") HoraBloqueada hora) {        
        return ControladorDeObjetos.saveObject(hora);
    }
    @WebMethod(operationName = "eliminarHoraBloqueada")
    public boolean eliminarHoraBloqueada(@WebParam(name = "hora") HoraBloqueada hora) {        
        return ControladorDeObjetos.deleteObject(hora);
    }
    @WebMethod(operationName = "buscarHorasBloqueadas")
    public List<HoraBloqueada> buscarHorasBloqueadas(@WebParam(name = "fechaDesde") Date fechaDesde, @WebParam(name = "fechaHasta") Date fechaHasta, @WebParam(name = "rut") String rut) {        
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction trans = session.beginTransaction();        
        Query q = session.createQuery("SELECT h FROM HoraBloqueada h WHERE h.rutProfesional='"+rut+"' AND h.fecha BETWEEN '"+fechaDesde+"' AND '"+fechaHasta+"'");        
        return q.list();
    }    
    @WebMethod(operationName = "buscarProgramasFonasaDePaciente")
    public List<ProgramaMedicoFonasa> buscarProgramasFonasaDePaciente( @WebParam(name = "rutPaciente")  String rutPaciente) {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction trans = session.beginTransaction();                        
        Query q = session.createQuery("from ProgramaMedicoFonasa p where p.rutPaciente='"+rutPaciente+"' AND p.visible=true");                        
        return q.list();
    }
    @WebMethod(operationName = "buscarProgramasDiprecaDePaciente")
    public List<ProgramaDipreca> buscarProgramasDiprecaDePaciente( @WebParam(name = "rutPaciente")  String rutPaciente) {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction trans = session.beginTransaction();                                    
        Query q = session.createQuery("from ProgramaDipreca p where p.rutPaciente='"+rutPaciente+"' AND p.visible=true");        
        return q.list();
    }    
    @WebMethod(operationName = "buscarProgramasJeafosaleDePaciente")
    public List<ProgramaMedicoJeafosale> buscarProgramasJeafosaleDePaciente( @WebParam(name = "rutPaciente")  String rutPaciente) {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction trans = session.beginTransaction();                
        Query q = session.createQuery("from ProgramaMedicoJeafosale p where p.rutPaciente='"+rutPaciente+"' AND p.visible=true");        
        return q.list();
    }    
    
    @WebMethod(operationName = "filtrarPacientes")
    public List<Paciente> filtrarPacientes(@WebParam(name = "buscar") String buscar) {
        
        Session s = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction trans = s.beginTransaction();
        Criteria c = s.createCriteria(Paciente.class).add(Restrictions.and(Restrictions.eq("visible", true), 
                Restrictions.or(
                Restrictions.or(
                Restrictions.or(
                Restrictions.ilike("nombres", "%" + buscar + "%"), 
                Restrictions.ilike("apellidoPaterno", "%" + buscar + "%")), 
                Restrictions.ilike("apellidoMaterno", "%" + buscar + "%")), 
                Restrictions.ilike("rut", "%" + buscar + "%"))));                      
        List l = c.list();
        s.close();
        return l;
    }    
    @WebMethod(operationName = "calculaNumeroCitasDeUnPrograma")
    public int calculaNumeroCitasDeUnPrograma(@WebParam(name = "numeroPrograma") String numeroPrograma, @WebParam(name = "tipoPrograma") String tipoPrograma) {
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction trans = session.beginTransaction();
        Query q = session.createQuery("from Cita c where c.idPrograma='"+numeroPrograma+"' AND c.tipoPrograma='"+tipoPrograma+"'");
        return q.list().size();
    }
}
